import i18n from '@src/locales'
/* data */
import BizListViewComputed from '@src/component/business/BizListView/BizListViewComputed'
/* entity */
import Field from '@model/entity/Field'
import TaskType from '@model/entity/TaskType'
/* enum */
import StorageKeyEnum from '@model/enum/StorageKeyEnum'
import ElementTableSortOrderEnum from '@model/enum/ElementTableSortOrderEnum'
import ComponentNameEnum from '@model/enum/ComponentNameEnum'
import SortModeEnum from '@model/enum/SortModeEnum'
/* model */
import MsgModel from '@model/MsgModel'
import Column from '@model/types/Column'
import { PLEASE_SELECT_EXPORT_DATA_MESSAGE } from '@src/model/const/Alert'
import { commonUseItemType } from '@src/component/AdvancedSearch/advancedSearch'
import { TABLE_HEIGHT_MIN } from '@src/model/const/Number'
/* util */
import Log from '@src/util/log.ts'
import { safeNewDate } from '@src/util/time';
import Platform from '@src/util/platform'
import { formatDate } from 'pub-bbx-utils'
import { storageGet, storageSet, StorageSetType } from '@src/util/storage.ts'
import { fieldArrayToObject } from '@src/util/array'


class BizListViewMethods<T, P> extends BizListViewComputed<T, P> {
  /* 当前工单类型 */
  public currentTaskType: TaskType | null = null

  /**
   * @description: 构建高级搜索面板参数
   * @return {Record<string, any>} 参数
   */  
  public buildAdvancedSearchParams(): Record<string, any> {
    // 获取高级搜索参数
    return this.BaseSearchPanelComponent?.buildParams() || {}
  }
  
  /**
   * @description 构建导出参数
   * @param {string[]} checkedArray 选择的导出列key
   * @param {string[]} ids 选择的id列表
   * @param {Boolean} exportOneRow 多选类型的字段在导出时，不同值在同一个单元格中显示（例如：字段名称：1/2/3/4）
   * @return {Record} 导出参数
   */
  public buildExportParams(checkedArray: any, ids: string[], exportOneRow?: boolean): Record<string, any> {
    return {}
  }
  
  /**
   * @description 检测导出条数
   * @return {String | null}
  */
  public checkExportCount(ids: string[], max: number): string | null {
    // 是否为导出全部
    const isExportAll = !ids || ids.length == 0
    // 页面全部数量
    const pageTotalCount = Number(this.page?.total || this.page?.totalElements)
    
    return (
      isExportAll && pageTotalCount > max
        ? i18n.t('common.base.tip.exportLimit', { max }) as string
        : null
    )
  }
  
  /**
   * @description: 删除事件
   * @return {void}
   */  
  public deleteHandler() {}
  
  public endLoading() {
    this.loading = false
  }
  
  /**
   * @description: 导出任务
   * @param {boolean} isExportAll 是否为导出全部
   * @return {void | Promise<boolean>}
   */  
  public exportTask(isExportAll: boolean = false): void | Promise<boolean> {
    // @ts-ignore
    this.$track.clickStat(this.$track.formatParams(`${isExportAll ? 'EXPORT_ALL' : 'EXPORT'}`, null , 'MORE_ACTIONS'));

    // 导出文件名
    const exportFileName = `${formatDate(safeNewDate(), 'YYYY-MM-DD')} ${this.exportFileName}.xlsx`
      
    if (!isExportAll && this.selectedIds.length <= 0) {
      return Platform.alert(PLEASE_SELECT_EXPORT_DATA_MESSAGE)
    }
    
    const exportIds = isExportAll ? [] : this.selectedIds
    
    this.openExportPanel(exportIds, exportFileName)
  }
  
  /**
   * @description 导出提示
  */
  public exportAlert(result: MsgModel<any>, params = {}) {
    Platform.alert(result.message)
  }
  
  /**
   * @description: 获取表格列表数据
   * @return {void}
   */  
  public fetchTableListData(): void {}
  
  /**
   * @description: 从缓存获取数据
   * @param {StorageKeyEnum} key 缓存键名
   * @param {StorageSetType} data 需要获取的数据
   * @return {Promise<T[]>}
   */  
  // public async getDataWithStorage<T = Field>(key: StorageKeyEnum, defaultValue: any): Promise<T[]> {
  public async getDataWithStorage<T = Field>(key: string, defaultValue: any): Promise<T[]> {
    return storageGet(key, defaultValue, this.storageModule)
  }
  
  /** 
   * @description 获取属性
  */
  public getAttributes() {
    const classNames: string[] = [ComponentNameEnum.BizListView, 'common-list-container__v2']
    
    return {
      class: classNames,
      directives: [
        {
          name: 'loading',
          value: this.loading
        }
      ]
    }
  }

  /** 
   * @description 获取loading
  */
  public getLoading() {
    
    return {
      directives: [
        {
          name: 'loading',
          value: this.loading
        }
      ]
    }
  }
  
  /**
   * @description: 分页当前页码数据变化事件
   * @param {number} pageNum 页码数
   * @return {void}
   */  
  public onPaginationPageNumChangedHandler(pageNum: number): void {
    this.searchParams.pageNum = pageNum
    
    this.search()
  }

  /**
   * @description: 表格选择项化事件
   * @param {any[]} selection 选择项
   * @return {void}
   */  
  public onChangeSelectionHandler(selection: any[]): void {
    this.multipleSelection = selection
    this.$nextTick(()=>{
      this.knowTableContainerHeight();
    })

  }
  
  /**
   * @description: 分页当前页大小数据变化事件
   * @param {number} pageSize 页大小
   * @return {void}
   */  
  public onPaginationPageSizeChangedHandler(pageSize: number): void {
    if(this.pageSizeStorageKey !== 'empty') {
      this.saveDataToStorage(this.pageSizeStorageKey, JSON.stringify({'pageSize': pageSize}))
    }
    
    this.searchParams.pageSize = pageSize
    this.searchParams.pageNum = 1
    
    this.search()
  }
  
  /**
   * @description: 打开导出面板
   * @param {string} exportIds 导出的ids列表
   * @param {string} fieldName 导出的文件名
   * @return {void}
   */  
  public openExportPanel(exportIds: string[], fieldName: string): void {
    // @ts-ignore
    this.BaseExportComponent?.open(exportIds, fieldName)
  }
  
  /**
   * @description: 重置搜索
   * @return {void}
   */
  public resetSearch() {
    // @ts-ignore
    this.$track.clickStat(this.$track.formatParams('RESET_SEARCH'));

    window.location.reload()
  }
  
  public reRenderTable() {
    // 重新渲染表格
    this.BizTableComponent?.outsideReRenderTable()
  }

  // 关键字搜索
  public keyWordSearch() {
    // @ts-ignore
    this.$track.clickStat(this.$track.formatParams('KEYWORD_SEARCH'));

    // 关键字搜索的pageNum需要重置为1，如果不重置则视为在当前page搜索关键字
    this.searchParams.pageNum = 1
    this.search()
  }
  
  /**
   * @description: 搜索
   * @return {void}
   */
  public search() {
    Log.succ(Log.Start, this.search.name)
    this.fetchTableListData()
  }
  
  /**
   * @description: 设置高级搜索列宽
   * @param {number} columnNum 列宽 几栏
   * @return {void}
   */
  public setAdvanceSearchColumnWidth(columnNum: number): void {
    this.columnNum = Number(columnNum)
  }
  
  /**
   * @description 保存更新的选择列信息 
  */
  public saveColumnStatus(value: { type: string, data: any[] }) {
    let columns = value.data || []
    const NewColumnMap = columns.reduce(
      (acc, col) => (acc[col.field] = col) && acc,
      {}
    )
    // 列对象
    const OldColumnsMap: Record<string, Column> = fieldArrayToObject<Column>(this.columns)
    let oldColumn: Column
    let newColumn: Column
    let field: string
    
    this.columns = columns.map((column: Column) => {
      field = column.field || ''
      oldColumn = OldColumnsMap[field] || {}
      newColumn = NewColumnMap[field] || {}
      
      oldColumn.show = newColumn.show
      oldColumn.width = newColumn.width
      oldColumn.fixLeft = newColumn.fixLeft
      
      return oldColumn
    })
    
    const showColumns = this.simplifyTableColumnsProperty(this.columns)
    // 保存到缓存
    this.saveDataToStorage(this.selectColumnStorageKey, showColumns)
    this.$message.success(this.$t('common.base.saveSuccess'));
    // 重新渲染表格
    this.reRenderTable()
  }
  
  /** 
   * @description 精简列属性
   * @param {Column[]} columns 需要精简的原始列数据列表
   * @returns {Column[]} 精简后的列数据列表
  */
  public simplifyTableColumnsProperty(columns: Column[]): Column[] {
    return (
      columns.map((column: Column) => ({
        field: column.field,
        show: column.show,
        width: column.width,
        fixLeft: column.fixLeft
      }))
    )
  }
  
  /**
   * @description: 保存数据到缓存
   * @param {StorageKeyEnum} key 缓存键名
   * @param {StorageSetType} data 需要保存的数据
   * @return {Promise<void>}
   */  
  // public async saveDataToStorage(key: StorageKeyEnum, data: StorageSetType): Promise<void> {
  public async saveDataToStorage(key: string, data: StorageSetType): Promise<void> {
    await storageSet(key, data, this.storageModule)
  }
  
  /**
   * @description: 表格排序变化事件
   * @param {Object} option 配置对象
   * @return {void}
   */  
  public sortChangeHandler(option: { prop?: any, order?: any } = {}): void {
    const { prop, order } = option
    const orderDetail = {
      column: prop,
      sequence: order === ElementTableSortOrderEnum.ASC ? SortModeEnum.ASC : SortModeEnum.DESC,
      isSystem: 1,
    }
    
    this.searchParams.orderDetail = orderDetail
    
    this.search()
  }
  
  /**
   * @description 显示已选择面板
   * @return {void}
   */  
  public showBaseSelectionPanelComponent(): void {
    this.BaseSelectionPanelComponent?.openPanel()
  }
  
  public startLoading() {
    this.loading = true
  }
  
  /**
   * @description: 切换高级搜索面板
   * @param {boolean} toggle 切换的状态
   * @return {void}
   */  
  public toggleAdvancedSearchPanel(toggle: boolean = true): void {
    this.visibleAdvancedSearchPanel = toggle
  }
  
  /**
   * @description: 切换已选择项
   * @param {any} rows 行数据
   * @return {void}
   */
  public toggleSelection(): void {
    this.BizTableComponent?.outsideClearSelection()
    this.multipleSelection = []
  }
  
  /**
   * @description: 切换选择列弹窗
   * @param {boolean} toggle 切换的状态
   * @return {void}
   */
  public toggleSelectColumnsDialog(toggle: boolean = true) {
    // @ts-ignore
    this.$track.clickStat(this.$track.formatParams('SELECT_COLUMN'));

    this.visibleSelectColumnDialog = toggle
    if (toggle) {
      this.BizSelectColumnComponent?.open(this.columns, this.currentTaskType)
    }
  }
  
  public toggleLoading() {
    this.loading = !this.loading
  }  
  /**
   * @des 可被覆盖
   */
  public computedListPxArray():Array<number> | []{
    return []
  }
  
  // 获取列表当前的可滚动高度
  public knowTableContainerHeight(otherArray?:Array<number> | []){
    let pxArray:Array<number> | [] = otherArray || this.computedListPxArray();
    let min = TABLE_HEIGHT_MIN;
    try {
      let window_ = window.innerHeight;
      let header:any = this.$refs.tableHeaderContainer?.offsetHeight || 0;
      let do_:any = this.$refs.tableDoContainer?.offsetHeight || 0;
      let footer:any = this.$refs.tableFooterContainer?.offsetHeight || 0;
      let selection:any = this.$refs.BaseSelectionBarComponent?.$el?.offsetHeight || 0;
      selection = selection ? selection + 8 : selection;
      console.log(window_, header, do_, footer, selection, 'window_, header, do_, footer, selection');
      console.log(pxArray, 'pxArray')
      let totalPx = 0;
      pxArray && pxArray.forEach(item=>totalPx = totalPx + item);
      min = window_ - header * 1 - do_ * 1  - footer * 1 - selection * 1 - totalPx;
      min = min > TABLE_HEIGHT_MIN ? min : TABLE_HEIGHT_MIN;
    } catch (error) {
      console.warn(error, 'error try catch');
    }
    console.log(min, 'minminmin')
    this.$set(this, 'tableContainerHeight', `${min}px`)
  }
  
  public changePackUp(){
    this.packUp = !this.packUp;
    this.$nextTick(()=> {
      this.knowTableContainerHeight()
    })
  };

  /**
   * 高级搜索
   * @param searchModel
   */
  public handleAdvancedSearch(searchModel: any){
    this.searchParams.pageNum = 1
    this.advancedSearchModel = searchModel;
    this.search();
  }

  /**
   * 重置搜索条件
   */
  public resetSearchModel(){
    this.advancedSearchModel = {
      conditions: [],
      systemConditions: [],
    };
  }

  /**
   * 改变高级搜索常用条件
   */
  public changeCommonUse(commonUseItem: commonUseItemType){}
}

export default BizListViewMethods
